package com.lczyfz.campusinfo.modules.thirdpay.web;

import com.lczyfz.campusinfo.common.utils.CharDataUtils;
import com.lczyfz.campusinfo.common.web.BaseController;
import com.lczyfz.campusinfo.modules.alipay.config.AlipayConfig;
import com.lczyfz.campusinfo.modules.campusinfopay.entity.CampusinfoPay;
import com.lczyfz.campusinfo.modules.campusinfopay.service.CampusinfoPayService;
import com.lczyfz.campusinfo.modules.sys.entity.User;
import com.lczyfz.campusinfo.modules.sys.utils.UserUtils;
import com.lczyfz.campusinfo.modules.thirdpay.service.PayCommonUtil;
import com.lczyfz.campusinfo.modules.thirdpay.service.WxpayService;
import com.lczyfz.campusinfo.modules.thirdpay.wxpay.WXPayUtil;
import com.lczyfz.campusinfo.modules.thirdpay.wxpay.impl.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 *创建人:陈文
 *创建时间:2017年8月15日 下午4:35:54
 *备注:
 */
@Controller
@RequestMapping(value = "alipayWeixin/pay")
public class AlipayWeixinController extends BaseController {
    //服务器异步通知
    @Autowired
    private CampusinfoPayService campusinfoPayService;
    @Autowired
    WxpayService wxpayService;

    //服务器异步通知
    @RequestMapping(value = "gateway")
    public void gateway(HttpServletRequest request) {
        logger.info("=====gateway===");
    }

    //生成微信订单url
    @RequestMapping(value = "order")
    public String pay(@RequestParam(value = "orderNo", required = true) String orderNo, HttpServletRequest request, Model model) {
        CampusinfoPay campusinfoPay = campusinfoPayService.get(orderNo);
        try {
            SortedMap<Object, Object> parameters = PayCommonUtil.getWXPrePayID(); // 获取预付单，此处已做封装，需要工具类
            User user = UserUtils.getUser();
            parameters.put("spbill_create_ip", user.getLoginIp());
            parameters.put("body", campusinfoPay.getGoodsName());
            parameters.put("out_trade_no", campusinfoPay.getId()); // 订单id这里我的订单id生成规则是订单id+时间
//            parameters.put("total_fee", "1"); // 测试时，每次支付一分钱，微信支付所传的金额是以分为单位的，因此实际开发中需要x100
            parameters.put("total_fee", Integer.parseInt(campusinfoPay.getAmount())*100+""); // 上线后，将代码放开
            String openId = user.getOpenId();
            parameters.put("openid", openId);
            // 设置签名
            String sign = PayCommonUtil.createSign("UTF-8", parameters);
            parameters.put("sign", sign);
            String requestXML = PayCommonUtil.getRequestXml(parameters); // 获取xml结果
            logger.debug("封装请求参数是：" + requestXML);
            // 调用统一下单接口
            HttpClientUtil util = HttpClientUtil.getInstance();
            String returnXml = util.httpPost(AlipayConfig.getOrderhttp(), "UTF-8", requestXML);
            Map<String, String> m = new HashMap<String, String>();
            m = WXPayUtil.xmlToMap(returnXml);
            if (m.get("return_code").equals("FAIL")) {
                logger.error(m.get("return_msg"));
                return null;
            } else {
                SortedMap<Object, Object> r_back = new TreeMap<Object, Object>();
                r_back.put("appId", m.get("appid"));
                r_back.put("timeStamp", System.currentTimeMillis() / 1000 + "");
                r_back.put("nonceStr", CharDataUtils.createRandomCharData(32));
                r_back.put("package", "prepay_id=" + m.get("prepay_id"));
                r_back.put("signType", "MD5");
                try {
                     r_back.put("paySign", PayCommonUtil.createSign("UTF-8",  r_back));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                model.addAttribute("timeStamp",  r_back.get("timeStamp"));
                model.addAttribute("nonceStr",r_back.get("nonceStr"));
                model.addAttribute("packageValue",r_back.get("package"));
                model.addAttribute("paySign", r_back.get("paySign"));
                model.addAttribute("appid", m.get("appid"));
                return "modules/campusinfopay/weixinpay";
            }
        } catch (Exception e) {
            e.printStackTrace();
            ;
            logger.error(e.getMessage());
            //     return null;
        }
        return null;
    }
}
